package area

import (
	"encoding/json"
	"strings"
)

type Area struct {
	ID      uint64 `json:"id"`
	Title   string `json:"title"`
	Level   uint8  `json:"level"`
	UpperID uint64 `json:"upperID"`
}

var areas []Area
var provinces []Area
var provinceToCity map[uint64][]Area
var cityToCounty map[uint64][]Area
var reverseIndex map[uint64]Area
var regionMap map[Region][]Area

func init() {
	// 将json字符串转为Area结构体
	var err error
	areas, err = parseArea(jsonStr)
	if err != nil {
		panic(err)
	}
	// 构建索引
	provinces, provinceToCity, cityToCounty = buildIndex(areas)
	reverseIndex = buildReverseIndex(areas)
	// 省排序
	sortAreasByID(provinces)
	// 按区域划分省
	regionMap = make(map[Region][]Area)
	for _, province := range provinces {
		switch province.ID {
		case 110000000000, 120000000000, 130000000000, 140000000000, 150000000000:
			regionMap[REGION_HUABEI] = append(regionMap[REGION_HUABEI], province)
		case 210000000000, 220000000000, 230000000000:
			regionMap[REGION_DONGBEI] = append(regionMap[REGION_DONGBEI], province)
		case 310000000000, 320000000000, 330000000000, 340000000000, 350000000000, 360000000000, 370000000000, 710000000000:
			regionMap[REGION_HUADONG] = append(regionMap[REGION_HUADONG], province)
		case 410000000000, 420000000000, 430000000000:
			regionMap[REGION_HUAZHONG] = append(regionMap[REGION_HUAZHONG], province)
		case 440000000000, 450000000000, 460000000000, 810000000000, 820000000000:
			regionMap[REGION_HUANAN] = append(regionMap[REGION_HUANAN], province)
		case 500000000000, 510000000000, 520000000000, 530000000000, 540000000000:
			regionMap[REGION_XINAN] = append(regionMap[REGION_XINAN], province)
		case 610000000000, 620000000000, 630000000000, 640000000000, 650000000000:
			regionMap[REGION_XIBEI] = append(regionMap[REGION_XIBEI], province)
		}
	}
	// 加载IP归属地数据
	initRegion()
}

// parseArea 将json字符串转为Area结构体
func parseArea(jsonStr string) ([]Area, error) {
	var areas []Area
	err := json.Unmarshal([]byte(jsonStr), &areas)
	if err != nil {
		return nil, err
	}
	return areas, nil
}

func GetProvinces() []Area {
	return provinces
}

func GetCitiesByProvinceID(provinceID uint64) []Area {
	cities := provinceToCity[provinceID]
	sortAreasByID(cities) // 对城市进行排序
	return cities
}

// GetCountiesByCityID 获取指定市ID的县列表
func GetCountiesByCityID(cityID uint64) []Area {
	counties := cityToCounty[cityID]
	sortAreasByID(counties) // 对县进行排序
	return counties
}

// GetUpperArea 获取指定区域ID的上级区域数据
func GetUpperArea(currentID uint64) (Area, bool) {
	if area, exists := reverseIndex[currentID]; exists {
		// 如果本身等级为1，则表明是省级的，无上级区域
		if area.Level == 1 {
			return Area{}, false
		}
		if upperArea, exists := reverseIndex[area.UpperID]; exists {
			return upperArea, true
		}
	}
	return Area{}, false
}

// SearchProvinceByTitle 根据省名称搜索地区ID
func SearchProvinceByTitle(keyword string) (Area, bool) {
	// 遍历查找
	for _, province := range provinces {
		if strings.Contains(province.Title, keyword) {
			return province, true
		}
	}
	return Area{}, false
}

func SearchProvincesByTitle(keyword string) []Area {
	var results []Area
	// 遍历查找
	for _, province := range provinces {
		if strings.Contains(province.Title, keyword) {
			results = append(results, province)
		}
	}
	return results
}

// IsExistingCityById 根据市ID判断市是否存在
func IsExistingCityById(cityId uint64) (Area, bool) {
	// 只需要判断有没有上级省就行
	province, exists := GetUpperArea(cityId)
	if !exists {
		return Area{}, false
	}
	// 再通过省ID获取市列表
	cities := provinceToCity[province.ID]
	for _, city := range cities {
		if city.ID == cityId {
			return city, true
		}
	}
	return Area{}, false
}

// SearchCityByTitle 根据市名称搜索指定ID的省下的市
func SearchCityByTitle(provinceId uint64, keyword string) (Area, bool) {
	// 获取市级列表
	cities := provinceToCity[provinceId]
	// 遍历查找
	for _, city := range cities {
		if strings.Contains(city.Title, keyword) {
			return city, true
		}
	}
	return Area{}, false
}

// SearchCitiesByTitle 根据市名称搜索指定ID的省下的市
func SearchCitiesByTitle(provinceId uint64, keyword string) []Area {
	var results []Area
	// 获取市级列表
	cities := provinceToCity[provinceId]
	// 遍历查找
	for _, city := range cities {
		if strings.Contains(city.Title, keyword) {
			results = append(results, city)
		}
	}
	return results
}

// GetAreaDetailByID 获取指定ID的区域详情
func GetAreaDetailByID(areaID uint64) *Area {
	exists, ok := reverseIndex[areaID]
	if !ok {
		return nil
	}
	return &exists
}

func GetProvincesByRegion(region Region) []Area {
	return regionMap[region]
}
